import { Controller, Get, Header, Req, Post, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBody, ApiQuery, ApiBearerAuth} from '@nestjs/swagger';
import { AlipayService } from '../../services/alipay/alipay.service';
import { Request } from 'express';
import * as moment from 'moment';
import { OrderService } from '../../services/order/order.service';
import { AuthGuard } from '@nestjs/passport';
import { UserService } from '../../services/user/user.service';

@ApiTags('alipay')
@Controller('api/alipay')
export class AlipayController {
  constructor(
    public alipayService:AlipayService,
    private orderService:OrderService
  ){}

  @Get('aliPay')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  //@Header("Content-Type","text/html; charset=utf-8")
  @ApiQuery({name:"order_id",description:"订单id",required:true})
  async aliPay(@Req() req){
    const querys = req.query;
    const order=await this.orderService.findOne({
      where:{
        'id':parseInt(querys['order_id'])
      },
      select:['order_sn','user_id','actual_price','id'],
      relations:['orderGoods']
    });
    if(!order||order.user_id!=req.user.userId){
      return {
        code:201,
        msg:"订单不存在"
      }
    }
    //const tradeNo = 'alipay_'+moment().format('YYYYMMDDHHmmss');
    const url=await this.alipayService.tradePagePay(
      order.order_sn,order.actual_price.toString(),
      order.orderGoods[0].goods_name,order.orderGoods[0].goods_name
    );
    return {
      code:200,
      msg:'success',
      data:{
        url:url
      }
    }
  }

  @Get('aliWapPay')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  //@Header("Content-Type","text/html; charset=utf-8")
  @ApiQuery({name:"order_id",description:"订单id",required:true})
  async aliWapPay(@Req() req){
    const querys = req.query;
    const order=await this.orderService.findOne({
      where:{
        'id':parseInt(querys['order_id'])
      },
      select:['order_sn','user_id','actual_price','id'],
      relations:['orderGoods']
    });
    if(!order||order.user_id!=req.user.userId){
      return {
        code:201,
        msg:"订单不存在"
      }
    }
    //const tradeNo = 'alipay_'+moment().format('YYYYMMDDHHmmss');
    const url=await this.alipayService.tradeWapPay(
      order.order_sn,order.actual_price.toString(),
      order.orderGoods[0].goods_name,order.orderGoods[0].goods_name
    );
    return {
      code:200,
      msg:'success',
      data:{
        url:url
      }
    }
  }


  @Get('aliRefund')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  //@Header("Content-Type","text/html; charset=utf-8")
  @ApiQuery({name:"order_id",description:"订单id",required:true})
  @ApiQuery({name:"refund_amount",description:"退款金额",required:true})
  @ApiQuery({name:"refund_reason",description:"退款的原因说明"})
  async aliRefund(@Req() req){
    const querys = req.query;
    const order=await this.orderService.findOne({
      where:{
        'id':parseInt(querys['order_id'])
      },
      select:['order_sn','user_id','actual_price','id'],
      relations:['orderGoods']
    });
    if(!order||order.user_id!=req.user.userId){
      return {
        code:201,
        msg:"订单不存在"
      }
    }
    //const tradeNo = 'alipay_'+moment().format('YYYYMMDDHHmmss');
    const url=await this.alipayService.tradePageRefund(
      order.order_sn,querys['refund_amount'],querys['refund_reason']
    );
    return {
      code:200,
      msg:'success',
      data:{
        url:url
      }
    }
  }

  @Post('notify')
  async notify(@Req() req:Request){
    //console.log(req.body);
    const result=this.alipayService.checkNotify(req.body);
    if(!result){
      return {
        code:201,
        msg:"异常通知,已忽略"
      }
    }
    console.log(req.body);
    const order=await this.orderService.findOne({
      where:{
        'order_sn':req.body.out_trade_no
      }
    });
    if(req.body.trade_status=="TRADE_SUCCESS"){
      order.pay_status=1;
      order.pay_name=req.body.fund_bill_list[0].fundChannel;
      order.pay_time=req.body.gmt_payment;
      order.confirm_time=req.body.gmt_create;
    }
    this.orderService.repository.save(order);
    return {
      code:200,
      msg:"ok"
    };
  }
}
